from flask import request, Blueprint, render_template
from elasticsearch import Elasticsearch
from elasticsearch.exceptions import NotFoundError

import api_console
from zz import zz_code, zz_redis, zz_dingtalk, zz_return

app = Blueprint('route_es', __name__)


@app.before_request
def before_request():
    return api_console.before_request()


@app.errorhandler(NotFoundError)
def not_found_error(ex: NotFoundError):
    r = zz_return.of(ex.status_code)
    r.set_errmsg("not_found_error")
    r.set_data("info", ex.info)
    return r.to_json()


def get_es() -> Elasticsearch:
    return Elasticsearch(
        [
            zz_code.env("ES_HOST"),
        ],
        # 如果启用了安全特性，请提供用户名和密码
        http_auth=(zz_code.env("ES_USER"), zz_code.env("ES_PWD")),
        http_compress=True,  # 启用 HTTP 压缩
        retry_on_timeout=True,  # 遇到超时错误时重试
        max_retries=5  # 最多重试5次
    )


# 搜索
@app.route('/es/doc_search/<index>', methods=['POST'])
def doc_search(index):
    body = request.get_json()

    response = get_es().search(
        index=index,
        body=body
    )
    r = zz_return.of(0)
    r.set_data("time", zz_code.date_tostring())
    r.set_data("response", response['hits'])
    return r.to_json()


# 删除文档
@app.route('/es/doc_delete/<index>/<id>', methods=['GET'])
def doc_delete(index, id):
    response = get_es().delete(index=index, id=id)
    r = zz_return.of(0)
    r.set_data("time", zz_code.date_tostring())
    r.set_data("response", response)
    return r.to_json()


# 添加或者更新
@app.route('/es/doc_update/<index>/<id>', methods=['POST'])
def doc_update(index, id):
    body = request.get_json()

    response = get_es().index(index=index, id=id, body=body)

    r = zz_return.of(0)
    r.set_data("time", zz_code.date_tostring())
    r.set_data("response", response)
    return r.to_json()


@app.route('/es/doc_info/<index>/<id>', methods=['GET'])
def doc_info(index, id):
    response = get_es().get(index=index, id=id)

    r = zz_return.of(0)
    r.set_data("response", response)
    r.set_data("time", zz_code.date_tostring())

    return r.to_json()


@app.route('/es/analyzer_test', methods=['POST'])
def analyzer_test():
    body = request.get_json()
    response = get_es().indices.analyze(body=body)

    r = zz_return.of(0)
    r.set_data("response", response)
    r.set_data("time", zz_code.date_tostring())

    return r.to_json()
